package com.baoyouqun.API.wx;

import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


@Component
@Slf4j
public class WechatApiUtil {

    //    private static final String CODE2SESSION_URL =
//            "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
    private static final String CODE2SESSION_URL =
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 刷新微信session_key（小程序/移动应用）
     * 文档：https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     */
    public JSONObject refreshSessionKey(String appid, String refreshToken) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s",
                appid,
                refreshToken
        );

        try {
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<String> entity = new HttpEntity<>(headers);
//            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
//            log.info("微信刷新session_key响应：{}", response.getBody());
//            return JSONObject.parseObject(response.getBody());
            return JSONObject.parseObject(null);
        } catch (Exception e) {
            log.error("调用微信刷新session_key接口失败", e);
            throw new RuntimeException("调用微信接口失败");
        }
    }

    /**
     * 用code换取session_key和openid
     */
    public JSONObject getSessionInfo(String code) {
        String url = String.format(CODE2SESSION_URL, appid, secret, code);
        String response = restTemplate.getForObject(url, String.class);
        return JSONObject.parseObject(response);
    }
    // 其他已有方法（如getSessionInfo）保持不变...
}
